import { DEFAULT_SETTING } from '@/constants'
import { useSettingStore } from '@/stores'
import { Theme } from './interface'
import { getLightColor, getDarkColor } from '@/utils/color'
import { menuTheme } from '@/assets/styles/theme/menu'
import { asideTheme } from '@/assets/styles/theme/aside'
import { headerTheme } from '@/assets/styles/theme/header'
export const useTheme = () => {
  const settingStore = useSettingStore()
  const { primary, isDark, layout, asideInverted, headerInverted } = storeToRefs(settingStore)
  // init theme
  const initTheme = () => {
    switchDark()
  }
  const switchDark = () => {
    const html = document.documentElement as HTMLElement
    if (unref(isDark)) html.setAttribute('class', 'dark')
    else html.setAttribute('class', '')
    primaryPicker(unref(primary))
    setAsideTheme()
    setHeaderTheme()
  }
  const primaryPicker = (color: string) => {
    if (!color) {
      color = DEFAULT_SETTING.PRIMARY
      ElMessage({ type: 'success', message: `主题颜色已重置为 ${DEFAULT_SETTING.PRIMARY}` })
    }
    document.documentElement.style.setProperty('--el-color-primary', color)
    document.documentElement.style.setProperty(
      '--el-color-primary-dark-2',
      unref(isDark) ? `${getLightColor(color, 0.2)}` : `${getDarkColor(color, 0.3)}`
    )
    for (let i = 1; i <= 9; i++) {
      const primaryColor = unref(isDark) ? `${getDarkColor(color, i / 10)}` : `${getLightColor(color, i / 10)}`
      document.documentElement.style.setProperty(`--el-color-primary-light-${i}`, primaryColor)
    }
    settingStore.setGlobalState('primary', color)
  }
  // 设置菜单样式
  const setMenuTheme = () => {
    let type: Theme.ThemeType = 'light'
    if (asideInverted.value) type = 'inverted'
    if (isDark.value) type = 'dark'
    const theme = menuTheme[type!]
    for (const [key, value] of Object.entries(theme)) {
      document.documentElement.style.setProperty(key, value)
    }
  }
  // 设置侧边栏样式
  const setAsideTheme = () => {
    let type: Theme.ThemeType = 'light'
    if (asideInverted.value) type = 'inverted'
    if (isDark.value) type = 'dark'
    const theme = asideTheme[type!]
    for (const [key, value] of Object.entries(theme)) {
      document.documentElement.style.setProperty(key, value)
    }
    setMenuTheme()
  }

  // 设置头部样式
  const setHeaderTheme = () => {
    let type: Theme.ThemeType = 'light'
    if (headerInverted.value) type = 'inverted'
    if (isDark.value) type = 'dark'
    const theme = headerTheme[type!]
    for (const [key, value] of Object.entries(theme)) {
      document.documentElement.style.setProperty(key, value)
    }
    setMenuTheme()
  }
  return { primaryPicker, initTheme, switchDark }
}
